/*
 * @Author: zu1662
 * @LastEditor: zu1662
 * @Date: 2019-12-23 15:41:47
 * @LastEditTime : 2020-10-09 16:14:06
 * @Description: 权限插件，用于控制页面按钮等权限
 */
import store from '@/store'

const PerssionPlugin = {}

// v-if="$auth('product:product:update')"
PerssionPlugin.install = (Vue) => {
  Vue.prototype.$auth = permissions => {
    if (!permissions) return false

    const [type1, type2, type3, type4, type5] = permissions.split(':')
    const permissionList = store.getters.permissions
    let flag = false
    const firstRoles = permissionList && permissionList.find((firstType) => {
      return firstType.code === `${type1}`
    })

    const secondRoles = firstRoles && firstRoles.children && firstRoles.children.find((secondType) => {
      return secondType.code === `${type1}:${type2}`
    })

    const thirdlyRoles = secondRoles && secondRoles.children && secondRoles.children.find((actionType) => {
      return actionType.code === `${type1}:${type2}:${type3}`
    })

    // Determine whether there is a next level resource under the three-level menu. If there is no one, it means there are no all permissions buttons
    if (thirdlyRoles && thirdlyRoles.children && thirdlyRoles.children.length > 0) {
      const fourRoles = thirdlyRoles && thirdlyRoles.children.find((fourType) => {
        return fourType.code === `${type1}:${type2}:${type3}:${type4}`
      })
      if (fourRoles && Number(fourRoles.statusTag) === 1) {
        flag = true
      }

      const fifthRoles = fourRoles && fourRoles.children && fourRoles.children.find(buttonCode => buttonCode.code === `${type1}:${type2}:${type3}:${type4}:${type5}`)

      if (fifthRoles && Number(fifthRoles.statusTag) === 1) {
        flag = true
      }
    } else {
      // If actionRoles has no children but it's not undefined, that means it's a button under the secondary menu, release
      if (thirdlyRoles && Number(thirdlyRoles.statusTag) === 1) flag = true
    }

    return flag
  }
}

export default PerssionPlugin
